const app = getApp();
// 统一请求头
const BASE_URL = "http://127.0.0.1:38090/api";
// const BASE_URL = "http://47.115.204.20:38088/api";
const REGISTER_STATE = "register_state";

/**
 * 获取token
 * @returns {{token}}
 */
const requestHeader = function () {
    return {
        'token': wx.getStorageSync('token')
    }
};

/**
 * 统一请求模板
 * @param {*} url
 * @param {*} method
 * @param {Object} data 参数
 * @param {Object} header 请求头
 */
const request = (url, method, data, token) => {
    const _method = method.toLowerCase();
    return new Promise((resolve, reject) => {
        wx.request({
            url: BASE_URL + url,
            params: data,
            data: data,
            method: _method,
            header: !token ? requestHeader() : '',
            success(res) {
                const {data} = res;
                if (data.code === 200) {
                    console.log('[请求成功] => ' + url, data);
                    resolve(data)
                } else {
                    console.log('[请求成功] => ' + url, data);
                    if (data.code === 102 || data.code === 108) {
                        wx.showToast({
                            title: '登录中...',
                            icon: "none"
                        });
                        setTimeout(async () => {
                            wx.clearStorageSync('token');
                            await wxLogin();
                            wx.reLaunch({
                                url: '/pages/index/index',
                            })
                        }, 1000)
                    }
                    resolve(data)
                }
            },
            fail(err) {
                wx.showToast({
                    title: `网络繁忙, 请稍后再试!`,
                    icon: "none"
                });
                reject(err)
            }
        })
    })
};

// 用户登录
const wxLogin = () => {
    return new Promise((resolve, reject) => {
        wx.login({
            success: async (res) => {
                const r = await login(res.code);
                if (r.code == 200) {
                    saveInfo(r.data)
                    resolve({code: 200})
                } else if (r.code == 107) {
                    resolve({code: 107})
                }
            },
            fail: (err) => {
                wx.showToast({
                    title: '登录失败, 请重试',
                    icon: 'none'
                })
                reject({code: 500})
            }
        })
    })
};

// 用户注册
const wxRegister = () => {
    return new Promise((resolve, reject) => {
        wx.getUserProfile({
            desc: '展示用户信息',
            success: (result) => {
                const {encryptedData, iv, rawData, signature} = result
                wx.login({
                    timeout: 3000,
                    success: (response) => {
                        request('/user/wx-register', 'post', {
                            "code": `${response.code}`,
                            "encryptedData": `${encryptedData}`,
                            "iv": `${iv}`,
                            "rawData": `${rawData}`,
                            "signature": `${signature}`
                        }).then(res => {
                            if (res.code == 104) {
                                wxLogin().then(res1 => {
                                    if (res1.code == 200)
                                        resolve(res1)
                                    else
                                        reject(res1)
                                })
                            } else if (res.code == 200) {
                                saveInfo(res.data)
                                wx.setStorageSync(REGISTER_STATE, true);
                                resolve({code: 200})
                            } else {
                                wx.showToast({
                                    title: `注册失败, 请重新授权`,
                                    icon: 'none'
                                })
                            }
                        })
                    },
                    fail: (res) => {
                    },
                    complete: (res) => {
                    },
                })
            },
            fail: (res) => {
                console.log("fail: ", res)
            },
            complete: (res) => {
            },
        })
    })
};

// 初始化用户登录/注册状态
const initRegisterState = () => {
    console.log("【登录/注册状态初始化...】",);
    wx.setStorageSync(REGISTER_STATE, false);
    wx.login({
        success: async (res) => {
            const r = await login(res.code);
            if (r.code == 200) {
                saveInfo(r.data);
                wx.setStorageSync(REGISTER_STATE, true);
                console.log("【登录/注册状态初始化】", wx.getStorageSync(REGISTER_STATE))
            }
        }
    });
};

// 调用后端登录API
const login = (data) => {
    return request('/user/wx-login/' + data, 'post', '')
};

// 获取用户信息
const getInfo = () => {
  return request('/wx-user/', 'get', '');
};

// 更新用户信息
const updateInfo = (data) => {
  return request('/wx-user/', 'put', data);
};

// 保存用户信息
const saveInfo = (data) => {
    wx.setStorageSync("token", data.token)
    // app.globalData.token = data.token
    wx.setStorageSync('userInfo', JSON.stringify(data))
};

// 获取商品分类信息
const commodityTypeList = () => {
    return request('/commodity-type', 'get', '')
};

// 获取家政员列表
const fetchHousekeeperList = (params) => {
    return request('/housekeeper', 'get', params)
};

// 获取家政员详情
const fetchHousekeeperDetail = (id) => {
  return request('/housekeeper/detail/' + id, 'get')
};

// 获取商需求匹配信息
const fetchMatchList = (id) => {
  return request('/demand/match-list/' + id, 'get', '');
};

// 收藏商品
const collectCommodity = (id) => {
  return request('/commodity-collection/' + id, 'post', '');
};
// 取消收藏商品
const cancelCollectCommodity = (id) => {
    return request('/commodity-collection/' + id, 'delete', '');
};

// 获取地址
const fetchAddressList = (params) => {
  return request('/address-book/', 'get', params);
}

// 添加地址
const addAddress = (params) => {
  return request('/address-book/', 'post', params);
}

// 修改地址
const updateAddress = (params) => {
  return request('/address-book/', 'put', params);
}

// 删除地址
const deleteAddress = (id) => {
  return request('/address-book/' + id, 'delete', '');
}

// 获取订单列表
const fetchOrderList = (params) => {
  return request('/order/order-form/', 'get', params);
}

// 获取订单详情
const fetchOrderDetail = (id) => {
  return request('/order/order-form/detail/' + id, 'get', '');
}

// 获取服务类型选项
const fetchServiceTypeOptions = () => {
  return request('/service-type/options/', 'get', '');
}

// 获取文章分类
const fetchEssayTypeList = (params) => {
  if (!params) {
    params = '';
  }
  return request('/essay-type/', 'get', params);
}

// 发布需求
const publishDemand = (params) => {
  return request('/demand/', 'post', params);
}

// 获取需求列表
const fetchDemandList = (params) => {
  return request('/demand', 'get', params);
}

// 获取需求详情
const fetchDemandDetail = (id) => {
  return request('/demand/detail/' + id, 'get', '');
}

// (取消)文章点赞
const essayLike = (id) => {
  return request('/essay-like/' + id, 'post', '');
}
// (取消)文章收藏
const essayCollection = (id) => {
  return request('/essay-collection/' + id, 'post', '');
}

// 评论文章
const commentEssay = (params) => {
  return request('/essay-comment/', 'post', params);
}

// 获取文章评论列表
const fetchEssayCommentList = (params) => {
  return request('/essay-comment/', 'get', params);
}

// 回复评论
const replyComment = (params) => {
  return request('/essay-reply/', 'post', params);
}

// 获取回复列表
const fetchReplyList = (params) => {
  return request('/essay-reply/', 'get', params);
}

// 获取文章收藏列表
const fetchEssayCollectionList = (params) => {
  return request('/essay-collection/', 'get', params);
}

// 获取文章点赞列表
const fetchEssayLikeList = (params) => {
  return request('/essay-like/', 'get', params);
}

// 获取被点赞信息列表
const fetchByLikeList = (params) => {
    return request('/essay-like/listByLike', 'get', params);
}

// 获取被点赞信息列表
const getByLikeDetail = (id) => {
    return request('/essay-like/detail/' + id, 'get', '');
}

// 获取被收藏信息列表
const fetchByCollectionList = (params) => {
  return request('/essay-collection/listByCollection', 'get', params);
}

// 获取被收藏信息列表
const getByCollectionDetail = (id) => {
  return request('/essay-collection/detail/' + id, 'get', '');
}

// 获取被评论信息列表
const fetchByCommentList = (params) => {
  return request('/essay-comment/listComment', 'get', params);
}

// 获取被评论信息列表
const getByCommentDetail = (id) => {
  return request('/essay-comment/detail/' + id, 'get', '');
}

// 获取被回复信息列表
const fetchByReplyList = (params) => {
  return request('/essay-reply/listReply', 'get', params);
}

// 获取被回复信息列表
const getByReplyDetail = (id) => {
  return request('/essay-reply/detail/' + id, 'get', '');
}

// 获取未读消息信息
const getEssayMessage = () => {
  return request('/essay/message/', 'get', '');
}

// 下单
const createOrder = (params) => {
  return request('/order/order-form/housekeeper-to-order/', 'post', params);
}

// 需求下单
const createDemandOrder = (params) => {
  return request('/order/order-form/demand-to-order/', 'post', params);
}

// 支付
const payOrder = (id) => {
  return request('/order/order-form/pay/' + id, 'put', '');
}

// 开始服务
const startOrder = (id) => {
  return request('/order/order-form/start/' + id, 'put', '');
}
// 结束服务
const endOrder = (param) => {
    return request('/order/order-form/end/', 'put', param);
}

// 取消订单
const cancelOrder = (id) => {
  return request('/order/order-form/cancel/' + id, 'put', '');
}

// 订单/商品评价
const commentCommodity = (params) => {
  return request('/commodity-comment/', 'post', params);
}

// 获取各类未完成订单的数量
const getOrderMessage = () => {
  return request('/order-form/message/', 'get', '');
}

module.exports = {
    request,
    wxLogin,
    wxRegister,
    initRegisterState,
    BASE_URL,
    REGISTER_STATE,
    requestHeader,
    commodityTypeList,
    fetchHousekeeperList,
    fetchHousekeeperDetail,
    fetchMatchList,
    collectCommodity,
    cancelCollectCommodity,
    fetchAddressList,
    addAddress,
    updateAddress,
    deleteAddress,
    fetchOrderList,
    fetchOrderDetail,
    fetchEssayTypeList,
    publishDemand,
    fetchDemandList,
    fetchDemandDetail,
    essayLike,
    essayCollection,
    commentEssay,
    fetchEssayCommentList,
    replyComment,
    fetchReplyList,
    fetchEssayCollectionList,
    fetchEssayLikeList,
    fetchByLikeList,
    getByLikeDetail,
    fetchByCollectionList,
    getByCollectionDetail,
    fetchByCommentList,
    getByCommentDetail,
    fetchByReplyList,
    getByReplyDetail,
    getEssayMessage,
    createOrder,
    payOrder,
    startOrder,
    endOrder,
    cancelOrder,
    commentCommodity,
    getOrderMessage,
    getInfo,
    updateInfo,
    fetchServiceTypeOptions,
    createDemandOrder
};